package mt.dummy;

import mt.client.MicroTraderClient;
import mt.client.MicroTraderOnlineGui;
import mt.comm.ClientComm;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * This class is responsible for creating the first GUI of the application. This GUI should be able to provide a login form which can be used to either identify a 
 * user or to verify if the user has access to the application and to his data, placed at the server.
 * 
 * @author Grupo 2
 */

public class MicroTraderClientDummy implements MicroTraderClient {

	private JFrame frame = new JFrame("Login");
	private JPanel nnorthpanel;
	private JButton connect = new JButton("Connect to Server");
	private JTextField text = new JTextField();
	private ClientComm clientComm;
	
	
	/**
	 * Starts the login GUI. Regist the user.
	 * 
	 * @param clientCom				communication with the server in order to provide data exchange 
	 */
	@Override
	public void start(ClientComm clientComm) {

		this.clientComm=clientComm;
		frame.setLayout(new BorderLayout());
		frame.setSize(new Dimension(400, 200));
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		
		connect.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(text.getText().isEmpty())
					JOptionPane.showMessageDialog(frame,
						    "Please select a nickname",
						    "No name",
						    JOptionPane.WARNING_MESSAGE);
				else{
					System.out.println("OLA");
					frame.setVisible(false);
					
				connect();
				MicroTraderOnlineGui mips = new MicroTraderOnlineGui(new JFrame(), text.getText(), getClientComm());
								
				}
			}
		});
		
			frame.add(connect, BorderLayout.SOUTH);
			nnorthpanel = new JPanel();
			nnorthpanel.setLayout(new FlowLayout());
			text.setPreferredSize(new Dimension(70,20));
	
			nnorthpanel.add(new JLabel("What is your nickname?"));
			nnorthpanel.add(text);
			frame.add(nnorthpanel, BorderLayout.NORTH);
			frame.setVisible(true);
		
		
	}


	/**
	 * Establish a connection with the database server.
	 */
	private void connect() {
		  if(this.clientComm!=null){
		try {
			this.clientComm.connect("address", text.getText());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}else{
			   throw new NullPointerException();
		  }
		
	}
	
	/**
	 * Getter of clientComm.
	 * 
	 * @return clientComm			Returns the class which provides a communication with the server.
	 */
	private ClientComm getClientComm(){ return clientComm;}

}
